package com.howard.core;

import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.howard.utils.SQLScriptsUtils;

/**
 * 执行sql脚本管理bean
 * singleton pattern
 * 类级内部类  懒汉模式
 * 单例模式分为饿汉和懒汉模式两种，懒汉模式演化两个概念 一是LAZY，延迟创建实例，二是缓存原理
 * @author Howard He
 *
 */
@Component
public final class ExecSqlManager {

	private static final Logger logger = LoggerFactory.getLogger(ExecSqlManager.class);

	@Autowired
	private DataSource coreDataSource;

	private JdbcTemplate jdbcTemplate;

	/**
	 * 类级内部类 有static关键字
	 * @author Howard He
	 * @version 1.0
	 *
	 */
	private static class ExecSqlHolder {
		/** create instance*/
		private static ExecSqlManager instance = new ExecSqlManager();
	}

	@Autowired
	public void init() {
		jdbcTemplate = new JdbcTemplate(coreDataSource);
	}


	/**构造私有化*/
	private ExecSqlManager() {}

	public static ExecSqlManager getInstance()  {
		return ExecSqlHolder.instance;
	}

	/**
	 * 执行脚本操作
	 * @param sqls sql集合
	 */
	public void executeSqls(List<String> sqls) {
		if(CollectionUtils.isEmpty(sqls)) {
			logger.debug("no sql execute. cause : sqls is empty or null" );
			return;
		}
		for(String sql : sqls) {
			jdbcTemplate.execute(sql);
		}
	}

	/**
	 * 先要删除表，然后在创建表
	 * @param createSqls 创建表SQL
	 * @param dropSqls 删除表SQL
	 */
	public void initTables(List<String> createSqls, List<String> dropSqls) {
		if(CollectionUtils.isNotEmpty(dropSqls)) {
			executeSqls(dropSqls);
		}
		if(CollectionUtils.isEmpty(createSqls)) {
			logger.debug("no sql execute. cause : createSqls is empty or null" );
			return;
		}
		executeSqls(createSqls);
	}

	/**
	 *
	 * @param xml xml file name
	 */
	public void initTables(String xml) {
		List<String> dropSqls = SQLScriptsUtils.doScriptForList(xml, SQLScriptsUtils.DROP_NODE);
		List<String> createSqls = SQLScriptsUtils.doScriptForList(xml, SQLScriptsUtils.CREATE_NODE);
		initTables(createSqls, dropSqls);
	}
}
